<script lang="ts" setup>
import { uploadAPI } from "@/apis/common";
import { ArticleTargetAPI, publishAPI, updateAPI } from "@/apis/publish";
import { ChannelsAPI } from "@/apis/user";
import type { ChannelItem } from "@/types/article";
import type { PublishForm, PublishResponse } from "@/types/publish";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

// 声明表单
const publishForm = ref<PublishForm>({
  title: "",
  content: "",
  channel_id: 0,
  cover: {
    type: 1,
    images: [],
  },
});

// 频道列表
const channels = ref<ChannelItem[]>([]);
onMounted(async () => {
  const res = await ChannelsAPI();
  // console.log(res)
  channels.value = res.data.channels;
});

// 自定义上传
const onUpload = async (options: UploadRequestOptions) => {
  // console.log(options)
  const fd = new FormData();
  fd.append("image", options.file);
  const res = await uploadAPI(fd);
  // console.log(res.data.url)
  publishForm.value.cover.images.push(res.data.url);
};

// 图片
const handleRadioChange = () => {
  publishForm.value.cover.images = [];
};

// 返回表单
const PublishForm = ref<PublishResponse>({
  id: "",
});

// 发布文章校验规则
const publishFormRules = ref<FormRules<PublishForm>>({
  title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
  cover: [{ required: true, message: "请上传封面", trigger: "blur" }],
  channel_id: [
    { required: true, message: "请选择文章频道", trigger: "change" },
  ],
  draft: [{ required: true, message: "请选择是否为草稿", trigger: "blur" }],
});

// 获取表单实例
const publishFormRef = ref<FormInstance>();
const router = useRouter();

const onSubmit = async () => {
  // 校验表单
  try {
    await publishFormRef.value?.validate();
    await publishAPI(publishForm.value);
    // 发布文章
    ElMessage.success("发布成功");
    // 路由跳转
    router.push("article");
  } catch {}
};

// 回显数据
const fileList = ref<UploadUserFile[]>([]);
const updateData = async () => {
  const res = await ArticleTargetAPI(route.params.id as string);
  // console.log(res)
  publishForm.value = res.data;
  fileList.value = res.data.cover.images.map((item: string) => {
    return {
      url: item,
      name: "",
    };
  });
};
const route = useRoute();
if (route.params.id) {
  updateData();
}

const onUpdate = async (draft: boolean) => {
  // 校验表单
  try {
    await publishFormRef.value?.validate();
    const res = await updateAPI(
      publishForm.value,
      route.params.id as string,
      draft
    );
    console.log("res", res);
    // 修改文章
    ElMessage.success("修改成功");
    // 路由跳转
    router.push("article");
  } catch {}
};
</script>

<template>
  <el-card shadow="always">
    <!-- 头部：面包屑 -->
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <template v-if="$route.params.id">
          <el-breadcrumb-item to="/article">内容管理</el-breadcrumb-item>
          <el-breadcrumb-item>修改文章</el-breadcrumb-item>
        </template>
        <el-breadcrumb-item v-else>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 主体：表单 -->
    <el-form label-width="80px" :model="publishForm" :rules="publishFormRules">
      <el-form-item label="标题" prop="title">
        <el-input
          placeholder="请输入文章标题"
          style="width: 400px"
          v-model="publishForm.title"
        ></el-input>
      </el-form-item>

      <el-form-item label="频道" prop="channel_id">
        <el-select style="width: 240px" v-model="publishForm.channel_id">
          <el-option
            v-for="item in channels"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="封面：" prop="cover">
        <el-radio-group
          v-model="publishForm.cover.type"
          @change="handleRadioChange"
        >
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>
        <div>
          <el-upload
            fit="cover"
            list-type="picture-card"
            :http-request="onUpload"
            :limit="publishForm.cover.type"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <el-dialog>
            <img w-full alt="Preview Image" />
          </el-dialog>
        </div>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <div class="rant">
          <QuillEditor
            theme="snow"
            contentType="html"
            v-model:content="publishForm.content"
          />
        </div>
      </el-form-item>

      <el-form-item v-if="route.params.id">
        <el-button type="primary" @click="onUpdate(false)">修改文章</el-button>
        <el-button @click="onUpdate(true)">存入草稿</el-button>
      </el-form-item>
      <el-form-item v-else>
        <el-button type="primary" @click="onSubmit">发表文章</el-button>
        <el-button @click="onUpdate(true)">存入草稿</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  {{ publishForm }}
</template>

<style lang="less" scoped>
/* 样式 */
.rant {
  height: 200px;
  width: 600px;
}
</style>
<style>
.el-form-item__content {
  display: block;
}
.el-form-item__content {
  margin-top: 10px;
}
.el-form-item__label {
  margin-top: 10px;
}
.el-form-item__content {
  margin-top: 30px;
}
</style>
